# -*- coding: utf-8 -*-
import os

activate_this = os.environ['VITTUAL_ENV_PATH']
execfile(activate_this, dict(__file__=activate_this))

import MySQLdb
import datetime,time,calendar
import logging
import multiprocessing

log_file_name = 'auto_send_message_advance_log.txt'

logging.basicConfig(filename = os.path.join(os.getcwd(), log_file_name), \
    level = logging.INFO, filemode = 'a', \
    format = '%(asctime)s - %(levelname)s: %(message)s')

import sys
sys.path.append("..")

from app.utilities import DateAndTimeHandler, SmsHandler, NjuUtility
from config_user import DISTRICT_GULOU,DISTRICT_XIANLIN

def update_db():
    conn = MySQLdb.connect(host='localhost',port = 3306, \
       user='root', passwd='123456',db ='njusubsdb')
       
    cur = conn.cursor()
    cur_time = datetime.datetime.now()
    logging.info("invoke_time:"+str(cur_time))

    hrs = cur.execute("select * from his_rec where status=1")

    hisrecs = cur.fetchmany(hrs)
    for elem in hisrecs:
        consult_time = DateAndTimeHandler().YYTimeToDateTime(elem[6])

        time_delta = consult_time - cur_time

        if time_delta.days==0 and (time_delta.seconds>3600 and time_delta.seconds<=7200):
            
            logging.info("consult_time:"+str(consult_time))
            #logging.info("consult_time - cur_time, time delta is:"+str(time_delta))
            logging.info("his_id="+str(elem[0]))
            logging.info("\n")
            
            ss = cur.execute("select * from sch where id="+str(elem[5]))
            schs = cur.fetchmany(ss)
            if schs is None:
                continue    
            st = cur.execute("select * from stu where id="+str(elem[3]))
            stu = cur.fetchmany(st)
            if stu is None:
                continue
                
            yytime = str(elem[6])

            tostu = ""
            totch = ""
            if schs[0][6] == DISTRICT_GULOU:
                tostu = SmsHandler.buildSmsMsg(stu[0][3], "您有"+yytime+"时段鼓楼校区的职业咨询，请提前到达", 388170)
                totch = SmsHandler.buildSmsMsg(schs[0][3], "您有"+yytime+"时段鼓楼校区的咨询工作，请准时到达", 388170)
            elif schs[0][6] == DISTRICT_XIANLIN:
                tostu = SmsHandler.buildSmsMsg(stu[0][3], "您有"+yytime+"时段仙林校区的职业咨询，请提前到达", 388170)
                totch = SmsHandler.buildSmsMsg(schs[0][3], "您有"+yytime+"时段仙林校区的咨询工作，请准时到达", 388170)

            p1=multiprocessing.Process(target=SmsHandler.SendSmsMsg3,args=(totch,))
            p2=multiprocessing.Process(target=SmsHandler.SendSmsMsg3,args=(tostu,))
            p1.start()
            p2.start()
            p1.join()
            p2.join()

    cur.close()
    conn.commit()
    conn.close()
    
if __name__ == '__main__':
    try:
        while True:
            update_db()
            time.sleep(DateAndTimeHandler().sleep_time(1,0,0))
    except Exception as e:
        logging.error(str(e))
        pass
        
